package com.my.socket.nio.v10;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by ZhongGang
 * at 2018/7/4 11:13
 */
public class Processor {
    private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class);
    private static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);

    public void process(SelectionKey selectionKey) {
        EXECUTOR_SERVICE.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                    socketChannel.configureBlocking(false);
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    int read = socketChannel.read(byteBuffer);
                    if (read < 0) {
                        selectionKey.channel();
                    } else if (read == 0) {
                        return;
                    }
                    byteBuffer.flip();
                    String message = new String(byteBuffer.array());
                    LOGGER.info("read: {}", message);

                    byteBuffer = ByteBuffer.allocate(1024);
                    byteBuffer.put(message.getBytes());
                    byteBuffer.flip();
                    socketChannel.write(byteBuffer);
                    socketChannel.close();
                    LOGGER.info("write: {}", message);
                } catch (Exception e) {
                    LOGGER.error("exception caught, the error is {}", e.getMessage());
                }
            }
        });
    }
}
